<script setup>
import { onMounted, ref } from 'vue'
import {
  getEmpListApi,
  deleteEmpApi,
  addEmpApi,
  getEmpByIdApi,
  updateEmpApi,
} from '@/api/emp'
import { ElMessageBox, ElMessage } from 'element-plus'

// 查询条件
const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: '',
})

// 员工列表
const empList = ref([])

// 分页配置
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

// 新增、编辑、删除员工
const ids = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')
const empFormRef = ref(null)
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: [],
})

// 每页展示条数
const handleSizeChange = (val) => {
  pageSize.value = val
  getEmpList()
}
// 当前页
const handleCurrentChange = (val) => {
  currentPage.value = val
  getEmpList()
}
// 清空
const handleReset = () => {
  searchEmp.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: '',
  }
  getEmpList()
}

// 查询员工列表
const getEmpList = async () => {
  const res = await getEmpListApi({
    page: currentPage.value,
    pageSize: pageSize.value,
    ...searchEmp.value,
  })
  empList.value = res.data.rows
  total.value = res.data.total
}
// 获取职位名称
const getJobTitle = (job) => {
  switch (job) {
    case '1':
      return '班主任'
    case '2':
      return '讲师'
    case '3':
      return '教研主管'
    case '4':
      return '学工主管'
    case '5':
      return '咨询师'
    default:
      return '其他'
  }
}

// 职位列表
const jobList = ref([
  {
    id: '1',
    name: '班主任',
  },
  {
    id: '2',
    name: '讲师',
  },
  {
    id: '3',
    name: '教研主管',
  },
  {
    id: '4',
    name: '学工主管',
  },
  {
    id: '5',
    name: '咨询师',
  },
  {
    id: '6',
    name: '其他',
  },
])
// 部门列表
const deptList = ref([
  {
    id: '1',
    name: '研发部',
  },
  {
    id: '2',
    name: '市场部',
  },
])

// token
const token = ref(JSON.parse(localStorage.getItem('loginUser')).token || '')

// 图片上传之前
const onBeforeUpload = (val) => {
  if (val.type !== 'image/jpeg' && val.type != 'image/png') {
    ElMessage.error('上传头像图片只能是 jpeg 或者 png 格式')
    return false
  } else if (val.size > 1024 * 1024 * 10) {
    ElMessage.error('上传头像图片大小不能超过 10MB')
    return false
  }
  return true
}

// 图片上传成功
const onSuccess = (val) => {
  console.log(val, 'onSuccess')
  employee.value.image = val.data
  ElMessage.success('上传成功')
}

// 添加职位
const onAddJobExpr = () => {
  employee.value.exprList.push({
    date: [],
    begin: '',
    end: '',
    company: '',
    job: '',
  })
}

// 删除员工
const onDeleteEmp = async (id) => {
  ElMessageBox.confirm('确认删除?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(async () => {
      const res = await deleteEmpApi(id ? id : ids.value)
      if (res.code) {
        ElMessage.info('删除成功')
        getEmpList()
      } else {
        ElMessage.info('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('您已取消删除')
    })
}

// 编辑员工
const onUpdateEmp = async (id) => {
  const res = await getEmpByIdApi(id)
  if (res.code) {
    employee.value = res.data
    dialogTitle.value = '编辑员工'
    dialogVisible.value = true
    employee.value.exprList = res.data.exprList

    if (employee.value.exprList.length > 0) {
      employee.value.exprList.forEach((item) => {
        item.date = [item.begin, item.end]
      })
    }
  } else {
    ElMessage.info(res.msg)
  }
}
// 新增员工
const onAddEmp = () => {
  dialogTitle.value = '新增员工'
  dialogVisible.value = true
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: [],
  }
  empFormRef.value?.resetFields()
}

// 删除工作经历
const onDelExpr = (val) => {
  employee.value.exprList.splice(val, 1)
}

// 保存员工信息
const onSaveEmp = async () => {
  empFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = employee.value.id
        ? await updateEmpApi(employee.value)
        : await addEmpApi(employee.value)
      if (res.code) {
        dialogVisible.value = false
        ElMessage.success(employee.value.id ? '修改成功' : '新增成功')
        getEmpList()
      } else {
        ElMessage.error(res.msg)
      }
    }
  })
}
// 表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  phone: [
    // { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号' },
  ],
})

// 表格选择
const onSelectionChange = (selections) => {
  ids.value = selections.map((item) => item.id)
}

onMounted(() => {
  getEmpList()
})
</script>

<template>
  <el-form
    :inline="true"
    :model="searchEmp"
  >
    <el-form-item
      :label="'姓名'"
      width="50"
    >
      <el-input
        v-model="searchEmp.name"
        placeholder="请输入员工姓名"
      />
    </el-form-item>

    <el-form-item :label="'性别'">
      <el-select
        style="width: 100px"
        v-model="searchEmp.gender"
        placeholder="请选择"
      >
        <el-option
          label="男"
          value="1"
        />
        <el-option
          label="女"
          value="2"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="入职日期">
      <el-date-picker
        v-model="searchEmp.date"
        type="daterange"
        value-format="YYYY-MM-DD"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="
          (value) =>
            value != null
              ? ((searchEmp.begin = value[0]), (searchEmp.end = value[1]))
              : ((searchEmp.begin = ''), (searchEmp.end = ''))
        "
      />
    </el-form-item>

    <el-form-item>
      <el-button
        @click="getEmpList"
        type="primary"
        >查询</el-button
      >
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>

  <el-button
    type="primary"
    @click="onAddEmp"
  >
    + 新增员工
  </el-button>
  <el-button
    type="danger"
    :disabled="ids.length == 0"
    @click="onDeleteEmp()"
  >
    > - 批量删除
  </el-button>

  <!-- 表格 -->
  <el-table
    :data="empList"
    @selection-change="onSelectionChange"
    border
    class="mt-5"
  >
    <el-table-column
      type="selection"
      width="50"
      align="center"
    />
    <el-table-column
      prop="name"
      width="150"
      label="姓名"
      align="center"
    />
    <el-table-column
      width="120"
      label="头像"
      align="center"
    >
      <template #default="scope">
        <img
          :src="scope.row.image"
          style="width: 100px; height: 100px"
        />
      </template>
    </el-table-column>
    <el-table-column
      prop="deptName"
      width="120"
      label="部门名称"
      align="center"
    />
    <el-table-column
      prop="job"
      width="100"
      label="职位"
      align="center"
    >
      <template #default="scope">
        {{ getJobTitle(scope.row.job) }}
      </template>
    </el-table-column>
    <el-table-column
      prop="entryDate"
      width="150"
      label="入职日期"
      align="center"
    />
    <el-table-column
      prop="updateTime"
      width="270"
      label="最后操作时间"
      align="center"
    />
    <el-table-column
      width="auto"
      label="操作"
      align="center"
    >
      <template #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="onUpdateEmp(scope.row.id)"
          >编辑</el-button
        >
        <el-button
          type="danger"
          size="small"
          @click="onDeleteEmp(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <br />

  <!-- 分页 -->
  <el-pagination
    :page-sizes="[5, 10, 20, 30, 50]"
    :page-size="pageSize"
    :current-page="currentPage"
    :total="total"
    layout="total, sizes, prev, pager, next, jumper"
    @sizeChange="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 新增/修改员工对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
  >
    <el-form
      :model="employee"
      label-width="80px"
      :rules="rules"
      ref="empFormRef"
    >
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input
              v-model="employee.username"
              placeholder="请输入员工用户名，2-20个字"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="姓名"
            prop="name"
          >
            <el-input
              v-model="employee.name"
              placeholder="请输入员工姓名，2-20个字"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="性别"
            prop="gender"
          >
            <el-select
              v-model="employee.gender"
              placeholder="请选择性别"
            >
              <el-option
                label="男"
                value="1"
              />
              <el-option
                label="女"
                value="2"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="手机号"
            prop="phone"
          >
            <el-input
              v-model="employee.phone"
              placeholder="请输入员工手机号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select
              v-model="employee.jobId"
              placeholder="请选择职位"
            >
              <el-option
                v-for="item in jobList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input
              v-model="employee.salary"
              placeholder="请输入员工薪资"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select
              v-model="employee.deptId"
              placeholder="请选择部门"
            >
              <el-option
                v-for="item in deptList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="employee.entryDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload
              action="/api/upload"
              :headers="{ token }"
              :show-file-list="false"
              :before-upload="onBeforeUpload"
              :on-success="onSuccess"
              class="avatar-uploader"
            >
              <img
                v-if="employee.image"
                :src="employee.image"
                class="avatar"
              />
              <el-icon
                v-else
                class="avatar-uploader-icon"
              >
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button
              type="success"
              size="small"
              @click="onAddJobExpr"
              >+ 添加工作经历</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row
        :gutter="3"
        v-for="(item, index) in employee.exprList"
        :key="index"
      >
        <el-col :span="10">
          <el-form-item
            size="small"
            label="时间"
            label-width="80px"
          >
            <el-date-picker
              v-model="item.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="
                (value) =>
                  value != null
                    ? ((item.begin = value[0]), (item.end = value[1]))
                    : ((item.begin = ''), (item.end = ''))
              "
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item
            size="small"
            label="公司"
            label-width="60px"
          >
            <el-input
              placeholder="请输入公司名称"
              v-model="item.company"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item
            size="small"
            label="职位"
            label-width="60px"
          >
            <el-input
              placeholder="请输入职位"
              v-model="item.job"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item
            size="small"
            label-width="0px"
          >
            <el-button
              type="danger"
              @click="onDelExpr(index)"
              >- 删除</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        @click="onSaveEmp"
      >
        {{ employee.id ? '保存' : '新增' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>
